import { app, Tray, Menu, shell, BrowserWindow, ipcMain, dialog, nativeImage } from 'electron'
import { join } from 'path'
import { optimizer, is } from '@electron-toolkit/utils'
import getIcon from './iconExtractor'
import { rmSync } from 'fs'

const loadWindow = (window, html) => {
  const url = process.env['ELECTRON_RENDERER_URL']
  if (is.dev && url) {
    window.loadURL(`${url}/${html}.html`)
  } else {
    window.loadFile(join(__dirname, `../renderer/${html}.html`))
  }
}

let tray = null
const { openAtLogin } = app.getLoginItemSettings()
app.whenReady().then(() => {
  tray = new Tray(join(__dirname, '../../resources/icon.png'))
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '开机自启',
      type: 'checkbox',
      checked: openAtLogin,
      click: (e) => app.setLoginItemSettings({ openAtLogin: e.checked })
    }
  ])
  tray.setContextMenu(contextMenu)
})

const commonOptions = {
  show: false,
  resizable: false,
  maximizable: false,
  fullscreenable: false,
  titleBarStyle: 'hidden',
  backgroundColor: '#212121',
  // titleBarOverlay: { color: '#323232', symbolColor: '#7e8299', height: 40 },

  webPreferences: {
    preload: join(__dirname, '../preload/index.js'),
    sandbox: false,
    nodeIntegration: true,
    contextIsolation: false
  }
}

function createWindow() {
  const win = new BrowserWindow({
    ...commonOptions,
    width: 1600,
    height: 1000
  })
  ipcMain.on('useMain', (event, type, ...arg) => win[type]?.(arg))
  ipcMain.on('useSelf', (event, type, ...arg) => event.sender[type]?.(arg))

  win.on('show', () => win.webContents.send('show'))
  win.on('restore', () => win.webContents.send('show'))
  win.on('hide', () => win.webContents.send('hide'))
  win.on('minimize', () => win.webContents.send('hide'))

  // ipcMain.on('openModal', (event, type) => {
  //   const modal = new BrowserWindow({
  //     ...commonOptions,
  //     parent: win,
  //     modal: true,
  //     width: 800,
  //     height: 450
  //   })
  //   loadWindow(modal, type)
  //   modal.setMenu(null)
  //   modal.on('ready-to-show', modal.show)
  //   modal.on('closed', () => event.sender.send('openModal:return', type))
  // })

  ipcMain.on('selectDir', (event, arg) => {
    const path = dialog.showOpenDialogSync(win, { ...arg, properties: ['openDirectory'] })
    event.sender.send('selectDir:return', path)
  })
  ipcMain.on('selectExe', (event, defaultPath) => {
    const path = dialog.showOpenDialogSync(win, { defaultPath, filters: [{ name: 'exe', extensions: ['exe', 'bat'] }], properties: ['openFile'] })
    event.sender.send('selectExe:return', path)
  })
  ipcMain.on('openPath', (event, arg) => {
    shell.openPath(arg)
  })
  ipcMain.on('getFileIcon', (event, path) => {
    // app.getFileIcon(path, { size: 'large' }).then((res) => event.sender.send('getFileIcon:return', res))
    getIcon(path)
      .then((res) => {
        event.sender.send('getFileIcon:return', nativeImage.createFromPath(res))
        rmSync(res)
      })
      .catch((e) => dialog.showErrorBox('error', JSON.stringify(e)))
  })

  win.on('ready-to-show', () => {
    win.setMenu(null)
    win.show()
  })

  win.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })
  loadWindow(win, 'index')
}

app.whenReady().then(() => {
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})
